﻿using BLL.Base;
using CommandService;
using Entity;
using Entity.DbEntity;
using Entity.ViewEntity;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BLL.ASRepair
{
    public class ASRepairBLL : PubMethod
    {
        Commands cmd;
        LoginInfo userLogin;
        Tools.TxtLogHelper txt;
        ReturnResult rsl;
        OperateModel oper;
        public ASRepairBLL()
        {
            cmd = new Commands();
            userLogin = new LoginInfo();
            txt = new Tools.TxtLogHelper();
            oper = new OperateModel();
        }
     /// <summary>
        /// 生成销售信息表模型
        /// </summary>
        /// <param name="barCodes">一系列条码，用英文逗号隔开</param>
        /// <param name="cuCode">客户编码</param>
        /// <param name="salesDepartment">销售人员名称（实际业务员），不是销售部门编码</param>
        /// <param name="models">【引用传递】操作模型列表。如果列表内已经有对象，则追加对象。如果列表为Null，则自动新建列表。</param>
        /// <param name="errorMessage">【引用传递】传入空字符串。如果返回字符串非空，则表示方法执行失败。</param>
        public void FillSalesRecords(string barCodes, string cuCode, string salesDepartment, string createuser,
            ref List<OperateModel> models, ref string errorMessage)
        {
            try
            {
                if (models == null)
                {
                    models = new List<OperateModel>();
                }

                var internalModelList = new List<OperateModel>();
                var barArray = barCodes.Split(',');
                foreach (var bar in barArray)
                {
                    if (string.IsNullOrWhiteSpace(bar))
                    {
                        continue;
                    }
                    var rec = new DbSalesRecords();
                    rec.salesDate = DateTime.Now.ToString("yyyy-MM-dd");
                    rec.barCode = bar;
                    rec.cuCode = cuCode;
                    rec.createtime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                    rec.createuser = createuser;
                    rec.status = "Y";
                    rec.isDel = "0";
                    rec.salesStaff = salesDepartment;

                    var operModel = new OperateModel();
                    operModel.Data = rec;
                    operModel.Types = OperateModel.OperateType.Add;
                    internalModelList.Add(operModel);
                }

                models.AddRange(internalModelList);
            }
            catch (Exception ex)
            {
                errorMessage = ex.Message;
            }
    }
        /// <summary>
        /// 获取销售记录
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="typeCode"></param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult GetSalesRecordList(string pageIndex, string pageSize, string typeCode, ref string pageCount, string condition)
        {
            var rsl = new ReturnResult();
            try
            {
                var list = cmd.PageList<DbSalesRecord>("sr_SalesRecord", pageIndex, pageSize, "", "id desc", ref pageCount);
                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }

            return rsl;
        }

        public ReturnResult GetCustomerList(string pageIndex, string pageSize, string typeCode, ref string pageCount, string condition)
        {
            var rsl = new ReturnResult();
            try
            {
                var sb = new StringBuilder();
                sb.Append("isDel = 0 AND trType = '2' ");
                sb = CreateSelectCondition(sb, condition);
                var list = cmd.PageList<DbCustomer>("fun_Customs_info", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);

                rsl.Data = list;
                rsl.Result = true;

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }

            return rsl;
        }
        public ReturnResult GetRepairApply(string pageIndex, string pageSize, string typeCode, ref string pageCount, string condition)
        {
            var rsl = new ReturnResult();
            try
            {
                var sb = new StringBuilder();

                sb = CreateSelectCondition(sb, condition);
                var list = cmd.PageList<ViewApplyList>
                    ("V_SR_ApplyList", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);

                rsl.Data = list;
                rsl.Result = true;

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }

            return rsl;
        }

        public ReturnResult GetRepairHistory(string barCode)
        {
            var rsl = new ReturnResult();
            try
            {
                var sqlTemplate = "SELECT * FROM V_SR_RepairHistory WHERE barCode = '{0}'";
                var sql = string.Format(sqlTemplate, barCode);

                var dt = cmd.GetDataTable(sql);

                rsl.Result = true;
                rsl.Data = cmd.TableToDictionary(dt);

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }

            return rsl;
        }
        /// <summary>
        /// 获取销售条码信息
        /// </summary>
        /// <param name="barCode"></param>
        /// <returns></returns>
        public ReturnResult getSaleBarCodeInfoByBarCode(string barCode)
        {
            var rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select top 1 b.barCode,p.proName,p.spec,p.proCode,p.spec from bar_ProductBarCode_info b  ");
                sb.Append("inner join fun_Inventory_Info p on b.proCode=p.proCode ");
                sb.Append("where barCode='" + barCode + "'");
                var table = cmd.GetDataTable(sb.ToString());
                table.Columns.Add("salesDate");//销售人员
                table.Columns.Add("salesStaff");//销售人员
                table.Columns.Add("finishDate");//质保到期日
                table.Columns.Add("cuCode"); // 客户编码
                table.Columns.Add("cuName"); // 客户名称

                if (table.Rows.Count > 0)
                {
                    #region 查询销售记录信息
                    sb.Clear();
                    sb.Append("select top 1 * from sr_SalesRecord where ");
                    sb.Append("barCode='" + barCode + "' and status='Y' and isdel=0 ");
                    sb.Append("order by id desc");
                    var rTable = cmd.GetDataTable(sb.ToString());
                    if (rTable.Rows.Count > 0)
                    {
                        table.Rows[0]["salesDate"] = rTable.Rows[0]["salesDate"].ToString();
                        table.Rows[0]["salesStaff"] = rTable.Rows[0]["salesStaff"].ToString();
                        table.Rows[0]["finishDate"] = rTable.Rows[0]["finishDate"].ToString();
                        var cuCode = rTable.Rows[0]["cuCode"].ToString();
                        table.Rows[0]["cuCode"] = cuCode;
                        table.Rows[0]["cuName"] = getCustomNameByCode(cuCode);
                    }
                    #endregion
                    rsl.Data = cmd.TableToDictionary(table);
                    rsl.Result = true;
                }
                else
                {
                    rsl.Message = "该条码不存在";
                }

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 获取售后维修申请单编辑视图
        /// </summary>
        /// <param name="applyCode"></param>
        /// <returns></returns>
        public ReturnResult getEditApplyView(string applyCode)
        {
            var rsl = new ReturnResult();
            try
            {
                var sql = "select * from V_SR_EditApply WHERE applyCode ='" + applyCode + "' AND isDel = 0;";
                var dt = cmd.GetDataTable(sql);

                rsl.Data = cmd.TableToDictionary(dt);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }

            return rsl;
        }

        string getCustomNameByCode(string cuCode)
        {
            var sql = "select * from fun_Customs_info where cuCode = '" + cuCode + "' and trType = '2';";
            var dt = cmd.GetDataTable(sql);
            if (dt.Rows.Count > 0)
            {
                return dt.Rows[0]["cuName"].ToString();
            }
            else
            {
                return "";
            }
        }

        

      
    }


}
